package com.mgface.zookeeper.curator.function;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class 分布式锁 {

	public static void main(String[] args) throws Exception {
		String path = "/curator-locks";
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("localhost:2181")
				.retryPolicy(new ExponentialBackoffRetry(1_000, 3)).build();
		client.start();
		final InterProcessMutex ipm = new InterProcessMutex(client, path);
		final CountDownLatch cdl = new CountDownLatch(1);
		ExecutorService exec = Executors.newFixedThreadPool(10);
		for(int i=0;i<10;i++){
			exec.submit(()->{
				try {
					cdl.await();
					ipm.acquire();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
					String orderNo = sdf.format(new Date());
					System.out.println("订单号:"+orderNo);
					ipm.release();
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		exec.shutdown();
		cdl.countDown();
		exec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
		System.out.println("执行完毕....");
	}
	

}
